package com.czg.jsonschema2lombokpojo;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.Collections;

public class JsonPointerUtils {

    private static Map<String,String> SUBSTITUTIONS = new LinkedHashMap<String, String>() {{
        put("~", "~0");
        put("/", "~1");
        put("#", "~2");
        put(".", "~3");
        put("?", "~4");
    }};

    public static String encodeReferenceToken(final String s) {
        String encoded = s;
        for (Map.Entry<String,String> sub : SUBSTITUTIONS.entrySet()) {
            encoded = encoded.replace(sub.getKey(), sub.getValue());
        }
        return encoded;
    }
    
    public static String decodeReferenceToken(final String s) {
        String decoded = s;

        List<String> reverseOrderedKeys = new ArrayList<String>(SUBSTITUTIONS.keySet());
        Collections.reverse(reverseOrderedKeys);
        for (String key : reverseOrderedKeys) {
            decoded = decoded.replace(SUBSTITUTIONS.get(key), key);
        }

        return decoded;
    }
}
